#include "smTexture2DLod.h"
#include "smError.h" 

namespace ShaderManager
{

smTexture2DLod::smTexture2DLod(GLuint texture_unit)
: smTexture(texture_unit)
{

}

void smTexture2DLod::bind()
{
	glBindTexture(GL_TEXTURE_2D,id);
}

void smTexture2DLod::unbind()
{
	glBindTexture(GL_TEXTURE_2D,0);
}

void smTexture2DLod::load(int size, int lod, void **data, GLuint internal_format, GLuint format, GLuint type, bool linear, bool clamp)
{
	active();
	bind();

	if(clamp)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE  );
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE  );
	}
	else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
	}

	if(linear)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}
	else
	{
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL , 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod-1 );

	int s=1;
	for(int i=0 ; i < lod ; ++i)
	{
		glTexImage2D(
				GL_TEXTURE_2D,
				i, //Mipmap : aucun
				internal_format, //GL_RGB16
				size/s, size/s,
				0, //Largeur du bord : 0
				format, //GL_RGB,
				type,
				data[i]);
		s *= 2;
	}

	CheckGLError("Texture2DLod::load");
}

}